// https://medium.com/@homam/making-almost-every-non-interactive-web-page-work-offline-7798ed68baac

console.log('sw cache')

const cacheName = 'r2cache'

self.addEventListener('install', (event) => {
  console.log('install')
})

self.addEventListener('activate', (event) => {
  console.log('activate')
  event.waitUntil(self.clients.claim())
})

async function cachedFetch(request) {
  const pathname = new URL(request.url).pathname
  if (request.method != 'GET' || !pathname.startsWith('/cache'))
    return fetch(request)

  const cache = await caches.open(cacheName)
  console.log('request.url', request.url)
  const resp = await cache.match(request)
  if (resp) {
    console.log('from cache', request.url)
    return resp
  }
  else {
    console.log('not in cache', request.url)
    return fetch(request).then((response) => {
      // put the new response in the cache for next fetches
      // cache.put(request, response.clone())
      return response
    })
  }
}

self.addEventListener('fetch', event =>
  event.respondWith(cachedFetch(event.request)))
